import {POST_GENDER_ENUM} from '@/constants/post';
import {addPost} from '@/services/postService';
import {
    PageContainer,
    ProForm,
    ProFormDigit,
    ProFormItem,
    ProFormSelect,
    ProFormText,
    ProFormUploadButton,
    ProFormTextArea,
} from '@ant-design/pro-components';
import {useModel} from '@umijs/max';
import {AutoComplete, message, Form} from 'antd';
import type {UploadProps} from 'antd';
import React from 'react';

import {PostType} from "@/models/post";
import {uploadImage} from "@/services/fileService";

var url = "";

const photoUpload = (options: any) => {
    console.log(options.file)
    let formData = new FormData();
    formData.append("file", options.file);

    const data: PostType.PostPhotoRequest = {
        biz: 'user_avatar',
        file: formData.get("file")
    }

    uploadImage(data).then(res => {
        url = res.data;
        options.onSuccess(res, options.file);
    }).catch(err => {
        console.log(err)
        options.onError(err)
    });
}

const props: UploadProps = {
    name: 'file',
    action: '',
    headers: {
        'Content-Type': 'multipart/form-data;charset=UTF-8',
    },
    customRequest: photoUpload

}

/**
 * 帖子创建页面
 * @constructor
 */
const PostAddPage: React.FC<unknown> = () => {
    const {initialState} = useModel('@@initialState');
    const tagMap = initialState?.tagMap || {};

    /**
     * 根据分类获取标签选项数组
     * @param category
     */
    const getOptions = (category: string) => {
        if (!category || !tagMap[category]) {
            return [];
        }
        return tagMap[category].map((tag) => {
            return {
                value: tag.tagName,
                label: tag.tagName,
            };
        });
    };

    /**
     * 创建
     * @param fields
     */
    const doAdd = async (fields: PostType.PostAddRequest) => {
        const hide = message.loading('正在提交');
        try {
            if (url === "") {
                message.error("图片不能为空")
                hide()
                return;
            }
            fields.photo = url;
            await addPost(fields);
            message.success('创建成功');
            url = ""
        } catch (e: any) {
            message.error('创建失败，请重试！', e.message);
        } finally {
            hide();
        }
    };

    /**
     * AutoComplete 过滤函数
     * @param inputValue
     * @param option
     */
    const filterOption = (inputValue: string, option: any) =>
        option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;

    return (
        <PageContainer title="请留下您的大学秀帖子吧">
            <ProForm<PostType.PostAddRequest>
                onFinish={async (values) => {
                    doAdd(values);
                }}
                requiredMark={false}
                labelAlign="left"
                labelCol={{
                    xs: 24,
                    sm: 4,
                    md: 3,
                    xl: 2,
                }}
                wrapperCol={{
                    xs: 24,
                    sm: 20,
                    md: 16,
                    xl: 14,
                }}
                submitter={{
                    submitButtonProps: {
                        style: {
                            minWidth: 160,
                        },
                    },
                    render: (props, dom) => [...dom.reverse()],
                }}
            >
                <ProFormDigit min={18} max={100} name="age" label="年龄(必填)" rules={[{required: true, message: '需填写年龄'}]}/>

                <ProFormSelect
                    options={POST_GENDER_ENUM}
                    name="gender"
                    label="性别(必填)"
                    required
                    showSearch
                    rules={[{required: true, message: '需选择性别'}]}
                />
                <ProFormItem label="地点(必填)" name="place" required rules={[{required: true, message: '需填写地点'}]}>
                    <AutoComplete
                        placeholder="请输入"
                        options={getOptions('地点')}
                        filterOption={filterOption}
                    />
                </ProFormItem>
                <Form.Item label="专业(必填)" name="job" required rules={[{required: true, message: '需填写专业'}]}>
                    <AutoComplete
                        placeholder="请输入"
                        options={getOptions('专业')}
                        filterOption={filterOption}
                    />
                </Form.Item>
                <ProFormSelect
                    options={getOptions('学历')}
                    name="education"
                    label="学历(必填)"
                    required
                    showSearch
                    rules={[{required: true, message: '需填写学历'}]}
                />
                <ProFormSelect
                    options={getOptions('生活状态')}
                    name="loveExp"
                    label="生活状态(必填)"
                    required
                    showSearch
                    rules={[{required: true, message: '需填写生活状态!'}]}
                />
                <ProFormText
                    name="contact"
                    label="联系方式(必填)"
                    placeholder="请输入手机或微信号"
                    required
                    rules={[{required: true, message: '需填写联系方式'}]}
                />

                {/*<ProFormText*/}
                {/*  name="photo"*/}
                {/*  label="照片"*/}
                {/*  placeholder="请输入 url 地址"*/}
                {/*  rules={[{ type: 'url' }]}*/}
                {/*  required*/}
                {/*/>*/}

                <ProFormUploadButton
                    label="图片(必填)"
                    max={1}
                    name="photo"
                    fieldProps={{
                        ...props,
                    }}
                />

                <ProFormTextArea
                    name="content"
                    label="个人介绍(必填)"
                    required
                    fieldProps={{
                        autoSize: {minRows: 4},
                    }}
                    rules={[{required: true, message: '需填写个人介绍'}]}
                />
            </ProForm>
        </PageContainer>
    );
};

export default PostAddPage;
